<?php
	class DB
	{
		protected $host;
		protected $dbname;
		protected $user;
		protected $password;
		public function __construct($host, $dbname , $user, $password)
		{
			$this->host = $host;
			$this->dbname = $dbname;
			$this->user = $user;
			$this->password = $password;
			mysql_connect($host,$user,$password)||die("<h1>нет подключения к mySql серверу</h1>");
			mysql_select_db($dbname)||die("<h1>нет подключения к базе</h1>");
			mysql_query("set names 'utf8'");
		}
		
		protected function sql($sql)
		{
			return mysql_query($sql);
		}
		public function select(array $fields, array $tables, $condition="", $additional="")
		{
			$sql = "SELECT ";
			$sql .= implode($fields,",");
			$sql .= " FROM ".implode($tables,",");
			if(!empty($condition))
			{
				$sql .= " WHERE $condition";
			}
			$sql .= " ".$additional;
			$res = $this->sql($sql);
			// echo $sql;
			$arr = array();
			while($row = mysql_fetch_object($res))
			{
				$arr[] = $row; 
			}
			return $arr;
		}
		public function select_max($fields, $tables)
		{
			$sql = "SELECT MAX($fields) ";
			$sql .= " FROM ".$tables;
			$res = $this->sql($sql);
			$row = mysql_fetch_object($res);
			return $row;
		}
		public function insert($table, array $date)
		{
			$fields = $values = "";
			foreach($date as $f => $v)
			{
				$fields .= "`".$f."`,";
				$values .= "'$v',";
			}
			$fields = rtrim($fields, ",");
			$values = rtrim($values, ",");
			$sql = "INSERT INTO `$table`($fields) value($values)";
			//echo $sql;
			$this->sql($sql);
		}
		public function delete($table, $condition="")
		{
			$sql = "DELETE FROM `$table`";
			if(!empty($condition))
			{
				$sql .= " WHERE $condition";
			}
			//echo $sql;
			$this->sql($sql);
		}
		public function edit($table, $id, array $date)
		{
			$sql = "UPDATE `$table` SET ";
			foreach($date as $f => $v)
			{
				$sql .= "`$f` = '$v',";
			}
			$sql = rtrim($sql, ",");
			$sql .= " WHERE `id` = '$id'";
			//echo $sql;
			$this->sql($sql);
		}
		
		public function update($table, array $date, $condition="")
		{
			$sql = "UPDATE `$table` SET ";
			foreach($date as $f => $v)
			{
				$sql .= "`$f` = '$v',";
			}
			$sql = rtrim($sql, ",");
			if(!empty($condition))
			{
				$sql .= " WHERE $condition";
			}
			$this->sql($sql);
		}
		
		public function createTable($table, array $date)
		{
			$sql = "CREATE TABLE `$table` (";
			foreach($date as $d)
			{
				$sql .= "$d,";
			}
			$sql = rtrim($sql, ",");
			$sql .= ")";
			$this->sql($sql);
		}
		
	}
	
	
?>